import compressing from 'compressing';
import fs from 'node:fs';
import path from 'node:path';
import move from './move';
import request from './request';
export type DownloadGit = {
  url?: string | number;
  dir?: string;
  token?: string;
};
export const download = async (props?: DownloadGit) => {
  const { url, dir = process.cwd(), token = 'eyTQoy2Nd92Cv_KGso3L' } = props;
  // const url=`https://gitlab-front.ebonex.io/api/v4/projects/${projectId}/repository/archive.zip`
  console.log('download tpl', 'loading...');
  try {
    const res = await request(url, {
      type: 'buffer',
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    const [, filename] = /filename="(\S*).zip"/.exec(
      res.headers['content-disposition'],
    );
    const outputFile = path.join(dir, `${filename}.zip`);
    if (!fs.existsSync(outputFile)) {
      fs.mkdirSync(dir, { recursive: true });
      fs.writeFileSync(outputFile, 'utf8');
    }
    const output = fs.createWriteStream(outputFile);
    res.pipe(output);
    await compressing.zip.uncompress(outputFile, dir);
    move(path.join(dir, filename), dir);
    if (fs.existsSync(outputFile)) {
      fs.rmSync(outputFile);
    }
    console.log('download tpl successfully!');
    return Promise.resolve();
  } catch (e) {
    console.error('download tpl fail:', e);
    return Promise.reject(e);
  }
};
